package com.demo.webapp.security.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.filter.OncePerRequestFilter;

import com.demo.common.RegexUtils;
import com.demo.common.StringUtils;
import com.demo.core.model.Site;
import com.demo.webapp.context.MultisiteContextHolder;

/**
 * 站点访问状态管理器
 * <br/>根据当前用户访问的站点状态,动态控制是否可以进行访问。
 * <br/>当前点未设置指定跳转地址时,使用默认地址.
 * @author ryuu.kk
 *
 */
public class SiteAccessManagementFilter extends OncePerRequestFilter {

	// 忽略的请求地址
	private List<String> ignoreProcessesUrls;
	
	// 指定跳转地址.
	private String targetProcessesUrl = "/close.jsp";
	
	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		Site site = MultisiteContextHolder.getSite();
		if (site != null && site.getIsClose()) {
			// 站点拒绝访问.
			if (StringUtils.isNotEmpty(site.getDefaultUrl())) {
				// 网站默认地址
				targetProcessesUrl = site.getDefaultUrl();
			}
			if (ignoreProcessesUrls != null) {
				for (String url : ignoreProcessesUrls) {
					if (url.startsWith("/")) {
						url = request.getContextPath() + url;
					}
					if (RegexUtils.wildcardMatch(url, requiresUrl(request, response))) {
						filterChain.doFilter(request, response);
						return;
					}
				}
				//转发到拒绝页面
				request.getRequestDispatcher(targetProcessesUrl).forward(request, response);
				return;
			}
		}
		filterChain.doFilter(request, response);
	}
	
    /**
     * 得到url部分
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     */
    protected String requiresUrl(HttpServletRequest request, HttpServletResponse response) {
        String uri = request.getRequestURI();
        int pathParamIndex = uri.indexOf(';');

        if (pathParamIndex > 0) {
            // 去掉url上sessionid部分
            uri = uri.substring(0, pathParamIndex);
        }
        // 得到请求参数
        int queryParamIndex = uri.indexOf('?');

        if (queryParamIndex > 0) {
            // 取出请求参数
            uri = uri.substring(0, queryParamIndex);
        }

        return uri;
    }

	public void setIgnoreProcessesUrls(List<String> ignoreProcessesUrls) {
		this.ignoreProcessesUrls = ignoreProcessesUrls;
	}

	public void setTargetProcessesUrl(String targetProcessesUrl) {
		this.targetProcessesUrl = targetProcessesUrl;
	}
}
